<!--
 * @Author: yuqy
 * @Date: 2023-04-10 17:30:15
 * @LastEditors: yuqy
 * @LastEditTime: 2023-09-27 17:40:01
 * @Descripttion: -
-->
<template>
  <div class="white_board_wrap" ref="boardContainer">
    <v-icon
              large
              color="green darken-2"
            >
              mdi-domain
            </v-icon>
    <div id="white_board" class="white_board"/>
    <toolbar class="toolbar-style" @boardEdit='boardEdit' :memberNowState='memberNowState'/>
    <bottombar
      :boardScale='boardScale'
      :sceneIndex='sceneIndex' 
      :scenesTotal='scenesTotal' 
      class="bottombar-style" 
      @boardEdit='boardEdit' />
    <div class="no_write" v-if="!writeAble" />
  </div>
</template>
<script >
import { WhiteWebSdk, contentModeScale } from "white-web-sdk";
import { ref } from "vue";
import Toolbar from '@/components/toolsAgora/Toolbar.vue'
import Bottombar from '@/components/toolsAgora/Bottombar.vue'
let ROOM = {}
let whiteWebSdk = {}
export default {
  name: "whiteBoardWrapSelf",
  setup() {},
  created() {},
  components: {
    Toolbar,
    Bottombar
  },
  data() {
    return {
      boardScale: 1,
      sceneIndex: 0,
      scenesTotal: 1,
      memberNowState: {},
      Room: {},
      player: {},
      boxWidth: 0,
      boxHeight: 0,
      writeAble: true,
      wrapId: 'white_board',
      nickname: '我是哈哈哈',
      uuid: "1202df805d0211ee9092f53437514dfd",
      userId: String(parseInt(Math.random() * 100000)),
      appIdentifier: "3-TYgMU4EeyuEvUxWmBcNg/IolhCHVqFyxqjg",
      roomToken: "NETLESSROOM_YWs9X1NReDl6UnhDbzNRbTdHdSZleHBpcmVBdD0xNjk1ODE4OTk3MDIyJm5vbmNlPWU4OWMyZDc2LTNlYTgtNGU0Zi05ZmE4LTMyOTk5MGVhYTM0OCZyb2xlPTAmc2lnPTIyZjVkNzc4MWY5ZTgyNzk1ODU4NjFjYTFkZGMwNDZlYjFkZjNjMjllOTBjMWE4MzkwNTQ3N2YyOGFjZWEzNzEmdXVpZD0xMjAyZGY4MDVkMDIxMWVlOTA5MmY1MzQzNzUxNGRmZA"
    }
  },
  mounted() {
    let uuid = this.uuid;
    let appIdentifier = this.appIdentifier;
    let roomToken = this.roomToken;
    let boxWidth = this.$refs.boardContainer.offsetWidth
    let boxHeight = this.$refs.boardContainer.offsetHeight
    let maxWidthLimit = 16/9 // 固定长宽比
    let relLimit = boxWidth / boxHeight
    if (relLimit <= maxWidthLimit) { // 宽度较大
      this.boxWidth = boxWidth
      this.boxHeight = parseInt(boxWidth / 16 *9)
    } else {
      this.boxHeight = boxHeight
      this.boxWidth = parseInt(boxHeight / 9 * 16)
    }
    this.getFastBoardGainToken({ uuid, appIdentifier, roomToken });
  },
  methods: {
    /**
     * @name: 创建互动白板教室
     * @msg:
     * @return {*}
     */
    async createRoom() {
      let data = await getAction("/whiteboardclient/fastBoard/gainToken", {
        code: this.code
      });
      if (!data) return;
      this.getFastBoardGainToken(data);
    },
    /**
     * @name: 听讲互动端，只需要调用加入房间即可
     * @msg:
     * @return {*}
     */

    async joinRoom() {
      let data = await getAction("/whiteboardclient/fastBoard/joinRoom", {
        code: this.code
      });
      Toast.clear();
      if (!data) return;
      this.getFastBoardGainToken(data);
    },
    async getFastBoardGainToken({ uuid, appIdentifier, roomToken }) {
      if (!roomToken || roomToken == "null") {
        return this.$Message.error("参数异常, 请稍后重试");
      }
      if (!uuid || uuid == "null") {
        return this.$Message.error("参数异常, 请稍后重试");
      }
      // this.init({ appIdentifier: appIdentifier, uid: this.userId, uuid: uuid, roomToken: roomToken })
      let joinRoomParams = {
        userPayload: {
          nickName: this.nickName,
        },
        uuid,
        uid: this.userId,
        roomToken,
        disableNewPencil: false // 开启新铅笔工具
      };
      let roomCallbacks = {
        onKickedWithReason: res => {},
        onRoomStateChanged: res => {
          if (res.cameraState) {
            let cameraState =
              Math.floor(parseFloat(res.cameraState.scale * 100)) / 100;
            this.boardScale = cameraState;
          }
          // 画板改变了
          if (res.sceneState) {
            this.getNowScenes();
          }
        },
        onCanUndoStepsUpdate: res => {}
      };
      // let contentModeScale = WhiteWebSdk.contentModeScale;
      whiteWebSdk = new WhiteWebSdk({
        appIdentifier, // 从管理控制台获取 App Identifier
        disableNewPencilStroke: false // 开启笔锋
      });
      ROOM = await whiteWebSdk.joinRoom(joinRoomParams, roomCallbacks);
      // 允许本地序列化
      ROOM.disableSerialization = false;
      let wrapId = document.getElementById(this.wrapId);
      ROOM.bindHtmlElement(wrapId);
      ROOM.setCameraBound({
        centerX: 0,
        centerY: 0,
        width: this.boxWidth,
        height: this.boxHeight,
        minContentMode: contentModeScale(0.1),
        maxContentMode: contentModeScale(5)
      });
      let scale = parseInt((this.boxWidth / 1920) * 100) / 100;
      ROOM.moveCamera({ centerX: 0, centerY: 0, scale });
      // 获取用户状态
      this.memberNowState = ROOM.memberState();
      // 获取摄像头状态
      let cameraState = ROOM.state.cameraState;
      // ROOM.setViewMode('Follower') // Broadcaster 主播模式，Follower 跟随模式  Freedom自由模式
      // 获取视角状态
      let BroadcastState = ROOM.state.broadcastState;
      this.getEntireScenes();
      // // 获取当前所在场景
      this.getNowScenes();
      // 允许笔锋
      ROOM.disableNewPencil = false;
    },
    /**
     * @name: 控制书写
     * @msg:
     * @return {*}
     */
    controlWrite(bool) {
      this.writeRight = bool;
      ROOM.setWritable(bool);
    },
    boardEdit({ type, params }) {
      // 清空画板
      if (type == "cleanAll") {
        return ROOM.cleanCurrentScene();
      }

      // 设置字体颜色颜色
      if (type == "setHighlighterColor") {
        return ROOM.setMemberState({
          strokeColor: params.highlighterColor
        });
      }

      // 设置字体粗细
      if (type == "setBrushThin") {
        return ROOM.setMemberState({
          strokeWidth: params.thin
        });
      }

      if (type == "setToolType") {
        return ROOM.setMemberState({
          currentApplianceName: params.toolType
        });
      }

      // 设置五角星，三角形 菱形 对话气泡
      if (type == "setshapeType") {
        return ROOM.setMemberState({
          currentApplianceName: "shape",
          shapeType: params.toolType
        });
      }
      // 撤销
      if (type == "undo") {
        return ROOM.undo();
      }

      // 恢复
      if (type == "redo") {
        return ROOM.redo();
      }

      // 下一页
      if (type == "nextPage") {
        let entireScenes = Object.keys(ROOM.entireScenes());
        entireScenes.pop();
        entireScenes.unshift("/");
        if (this.sceneIndex + 1 >= entireScenes.length) return;
        this.sceneIndex++;
        let paths = entireScenes[this.sceneIndex];
        if (paths == "/") {
          // paths = '/init'
          paths = "/" + ROOM.entireScenes()["/"][0].name;
        }
        return paths && ROOM.setScenePath(paths);
      }

      // 上一页
      if (type == "prevPage") {
        let entireScenes = Object.keys(ROOM.entireScenes());
        entireScenes.pop();
        entireScenes.unshift("/");
        if (this.sceneIndex - 1 < 0) return;
        this.sceneIndex--;
        let paths = entireScenes[this.sceneIndex];
        if (paths == "/") {
          paths = "/" + ROOM.entireScenes()["/"][0].name;
        }
        return paths && ROOM.setScenePath(paths);
      }

      // 添加白板
      if (type == "addBoard") {
        this.getEntireScenes();
        let paths = "/" + (parseInt(Math.random() * 100000) + 100000);
        ROOM.putScenes(paths, "news");
        ROOM.setScenePath(paths);
        this.getEntireScenes();
        return this.getNowScenes();
      }

      // 删除场景
      if (type == "deleteBoard") {
        this.getEntireScenes();
        if (this.scenesTotal <= 1) return (this.sceneIndex = 0);
        let scenePath = ROOM.state.sceneState.contextPath;
        if (scenePath == "/") {
          // scenePath = '/init'
          scenePath = "/" + ROOM.entireScenes()["/"][0].name;
        }
        ROOM.removeScenes(scenePath);
        this.getEntireScenes();
        return this.getNowScenes();
      }

      // 缩放
      if (type == "setBoardScale") {
        // console.log(whiteWebSdk)
        // this.boardScale = params.boardScale
        let scale = params.boardScale;
        if (scale <= 0.1) scale = 0.1;
        if (scale >= 5) scale = 5;
        ROOM.moveCamera({ scale, animationMode: "continuous" });
      }
    },
    /**
     * @name: 获取当前房间所有的白板
     * @msg:
     * @return {*}
     */

    getEntireScenes() {
      let entireScenes = Object.keys(ROOM.entireScenes());
      this.scenesTotal = entireScenes.length;
    },
    /**
     * @name: 获取当前所选中的白板
     * @msg:
     * @return {*}
     */

    getNowScenes() {
      let entireScenes = Object.keys(ROOM.entireScenes());
      entireScenes.pop();
      entireScenes.unshift("/");
      let scenePath = ROOM.state.sceneState.contextPath;
      this.sceneIndex = entireScenes.indexOf(scenePath) || 0;
      if (this.sceneIndex <= -1) {
        this.sceneIndex = 0;
      }
    }
  },
  destroyed() {
    if (fastApp) {
      // 退出 Fastboard (从白板房间断开)
      fastApp.destroy();
    }
  }
};
</script>
<style>
:root {
  --fastboard-active-color: #fe6400;
}
.netless-whiteboard {
  background: #fff;
}
</style>
<style scoped lang='less'>
.read-the-docs {
  color: #888;
}
h1 {
  padding: 100px 0;
  color: #000;
  font-size: 48px;
}
.white_board_wrap {
  height: 100vh;
  background: #333;
  position: relative;
  .white_board {
    height: 100%;
  }
  .no_write {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: transparent;
    z-index: 999;
  }
}

.toolbar-style {
  transform: translateY(-50%) scale(0.8);
  position: fixed;
  left: 0;
  top: 50%;
  z-index: 99;
  box-shadow: 0px 2px 20px rgba(0,0,0,0.25 ) !important;
  /deep/ .v-list-item {
    justify-content: center;
  }
}

.bottombar-style {
  transform-origin: left;
  transform: scale(0.8);
  position: fixed;
  left: 8px;
  bottom: 4px;
  z-index: 99;
}
</style>
